package com.reef.impl;

import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.reef.dao.LendBookRepository;
import com.reef.dto.LendBookDto;
import com.reef.entity.Lend_book;
import com.reef.service.LendBookService;
@Service
public class LendBookServiceImpl implements LendBookService{
	@Autowired
	private LendBookRepository leRepository;
	public Lend_book insertLendbook(Lend_book lendbook) {
		return leRepository.save(lendbook);
	}
	public Page<Lend_book> findByBooknameAndReaName(LendBookDto lbDto, Pageable pageable) {
		Specification<Lend_book> spec = getSpec(lbDto);
		return leRepository.findAll(spec, pageable);
	}
	//封装一个多条件方法
	public Specification<Lend_book> getSpec(final LendBookDto lbDto) {
		return new Specification<Lend_book>() {

			public Predicate toPredicate(Root<Lend_book> root, CriteriaQuery<?> query,
					CriteriaBuilder criteriaBuilder) {
				//创建SQL表达式
				Predicate p = criteriaBuilder.conjunction();
				//声明表达式的集合
				List<Expression<Boolean>> list = p.getExpressions();
				if (lbDto.getReaderid()!=0) {
					list.add(criteriaBuilder.equal(root.get("readerid").as(Integer.class),lbDto.getReaderid() ));
				}
				if (lbDto.getReadername()!=null && lbDto.getReadername()!=" ") {
					list.add(criteriaBuilder.like(root.get("readername").as(String.class), "%"+lbDto.getReadername()+"%"));
				}
				if (lbDto.getBookname()!=null && lbDto.getBookname()!=" ") {
					list.add(criteriaBuilder.like(root.get("bookname").as(String.class), "%"+lbDto.getBookname()+"%"));
				}
				if (lbDto.getIsback()!=0) {
					list.add(criteriaBuilder.equal(root.get("isback").as(Integer.class),lbDto.getIsback() ));
				}
				if (lbDto.getIsoverdue()!=null && lbDto.getIsoverdue()!=" ") {
					list.add(criteriaBuilder.equal(root.get("isoverdue").as(String.class),lbDto.getIsoverdue() ));
				}
				return p;
			}
		};
		
		
	}
	public int updateByBackBookDate(String realdate, int isback, int sernum) {
		// TODO Auto-generated method stub
		return leRepository.updateByBackBookDate(realdate, isback, sernum);
	}
}
